import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import prisma from '@/lib/prisma';
import { z } from 'zod';

const resourceCreateSchema = z.object({
  title: z.string().min(1, 'Title is required'),
  type: z.string().min(1, 'Type is required'), // e.g., DOCUMENT, VIDEO, CODE, LINK, IMAGE, OTHER
  url: z.string().min(1, 'URL or path is required'), // 确保它是一个非空字符串即可
  experimentId: z.string(),
});

export async function POST(
  req: NextRequest,
  { params }: { params: { id: string } } // experimentId from URL segment
) {
  const session = await getServerSession(authOptions);
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
  }

  const experimentIdFromUrl = params.id;
  let payload;

  try {
    const body = await req.json();
    payload = resourceCreateSchema.parse(body);
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json({ error: 'Invalid input data', details: error.errors }, { status: 400 });
    }
    return NextResponse.json({ error: 'Invalid JSON payload' }, { status: 400 });
  }

  // Ensure experimentId from payload matches the one in URL, and also used for query
  if (payload.experimentId !== experimentIdFromUrl) {
    return NextResponse.json({ error: 'Experiment ID mismatch between payload and URL' }, { status: 400 });
  }

  try {
    const experiment = await prisma.experiment.findUnique({
      where: { id: experimentIdFromUrl },
      select: { createdById: true },
    });

    if (!experiment) {
      return NextResponse.json({ error: 'Experiment not found' }, { status: 404 });
    }

    // Authorization: Only admin or the teacher who created the experiment can add resources
    const isAdmin = session.user.role === 'ADMIN';
    const isExperimentCreator = experiment.createdById === session.user.id;

    if (!isAdmin && !isExperimentCreator) {
      return NextResponse.json({ error: 'Forbidden: You do not have permission to add resources to this experiment.' }, { status: 403 });
    }

    const newResource = await prisma.resource.create({
      data: {
        title: payload.title,
        type: payload.type,
        url: payload.url,
        experimentId: experimentIdFromUrl, // Use the validated experimentId from URL/payload
      },
    });

    return NextResponse.json({ message: 'Resource created successfully', resource: newResource }, { status: 201 });

  } catch (error) {
    console.error(`Error creating resource for experiment ${experimentIdFromUrl}:`, error);
    return NextResponse.json({ error: 'Internal server error while creating resource' }, { status: 500 });
  }
}

export async function GET(
    req: NextRequest,
    { params }: { params: { id: string } } // experimentId from URL segment
) {
    const session = await getServerSession(authOptions);
    // Allow authenticated users (students, teachers, admins) to view resources
    if (!session?.user?.id) {
        return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
    }

    const experimentId = params.id;

    try {
        const experimentWithResources = await prisma.experiment.findUnique({
            where: { id: experimentId },
            select: {
                id: true,
                title: true,
                resources: {
                    orderBy: {
                        createdAt: 'desc'
                    }
                }
            }
        });

        if (!experimentWithResources) {
            return NextResponse.json({ error: 'Experiment not found' }, { status: 404 });
        }
        
        // Optional: Further authorization if only authorized students can see resources
        // This depends on your ExperimentAuthorization model and logic
        // For now, assuming all authenticated users can see resources of an experiment they can access.

        return NextResponse.json({ resources: experimentWithResources.resources });

    } catch (error) {
        console.error(`Error fetching resources for experiment ${experimentId}:`, error);
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    }
} 